package com.project.server;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * 封装读取流的请求类
 */
public class Request {
    private String url;


    private Map<String, String> paraMap = new HashMap<>();

    public Request(InputStream in) {

        try {
            //将读取的信息读到byte数组
            byte[] by = new byte[1024];
            in.read(by);
            String str = new String(by).trim();

            if (str.startsWith("GET")) {

                this.paraGet(str);

            } else if (str.startsWith("POST")) {
                this.paraPost(str);
            }
        } catch (Exception e) {
        }
    }

    private void paraGet(String str) {
        str = str.split("\\s+")[1].substring(1);
        if (!str.contains("?")) {
            url = str;
        } else {
            String[] strAll = str.split("[?]");
            url = strAll[0];
            this.getMap(strAll[1]);
        }
    }

    private void getMap(String s) {
        String[] strings = s.split("&");
        for (String str : strings) {
            String[] newStr = str.split("=");
            if (newStr.length == 2) {
                paraMap.put(newStr[0], newStr[1]);
            } else if (newStr.length == 1) {
                paraMap.put(newStr[0], "");
            }
        }
    }

    private void paraPost(String str) {
        String[] strs = str.split("\\s+");
        url = strs[1].substring(1);
        str = strs[strs.length - 1];
        getMap(str);
    }

    public String getUrl() {
        return url;
    }

    /**
     * 根据表单名 返回
     * @param key
     * @return
     */
    public String getParameter(String key){
        return this.paraMap.get(key);
}

    @Override
    public String toString() {
        return "Request{" +
                "url='" + url + '\'' +
                ", paraMap=" + paraMap +
                '}';
    }

}
